/**
 * Created by XianTao on 2016/11/24
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.biz.wechat.lechuan.mobile.api.handler;

import org.lego.biz.wechat.lechuan.base.entity.UserPrize;
import org.lego.biz.wechat.lechuan.base.service.UserPrizeService;
import org.lego.biz.wechat.lechuan.mobile.api.service.ThirdPartService;
import org.lego.util.DateTimeUtil;
import org.lego.util.StringUtil;
import org.lego.wechat.base.msg.in.InMsg;
import org.lego.wechat.base.msg.in.InTextMsg;
import org.lego.wechat.base.msg.out.OutMsg;
import org.lego.wechat.base.msg.out.OutTextMsg;
import org.lego.wechat.portal.service.AbstractWechatHandler;
import org.lego.wechat.portal.service.WechatHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@Transactional
public class TextHandler extends AbstractWechatHandler {
    @Autowired
    private UserPrizeService userPrizeService;
    @Autowired
    private ThirdPartService thirdPartService;

    public boolean isMatch(InMsg inMsg) {
        return inMsg instanceof InTextMsg;
    }

    public OutMsg process(InMsg inMsg) {
        if (inMsg instanceof InTextMsg) {
            InTextMsg inTextMsg = (InTextMsg) inMsg;
            //检查是否输入了礼品代码，格式要求：【手机号：礼品代码】
            String content = inTextMsg.getContent();
            if (content.contains("：") || content.contains(":")) {
                String[] textArray = content.trim().split("[:：]");
                if (textArray.length == 2) {
                    List<UserPrize> byPrizeCodeAndTelephoneList = userPrizeService.findByPrizeCodeAndTelephone2(textArray[1], textArray[0]);
                    if (!ObjectUtils.isEmpty(byPrizeCodeAndTelephoneList)) {
                        StringBuilder replyMessage = new StringBuilder();
                        boolean isFirst = true;
                        for (UserPrize byPrizeCodeAndTelephone : byPrizeCodeAndTelephoneList) {
                            if (isFirst) {
                                isFirst = false;
                            } else {
                                replyMessage.append("\n\n");
                            }
                            //检查此用户对于此图文是否已经领奖
                            UserPrize byOpenIdAndNewsId = userPrizeService.findOneByOpenIdAndNewsId(inTextMsg.getFromUserName(), byPrizeCodeAndTelephone.getPushNews().getId());
                            if (ObjectUtils.isEmpty(byOpenIdAndNewsId)) {
                                //检查此手机号对于此图文是否已经领奖
                                UserPrize byTelephoneAndNewsId = userPrizeService.findOneByTelephoneAndNewsId(textArray[0], byPrizeCodeAndTelephone.getPushNews().getId());
                                if (ObjectUtils.isEmpty(byTelephoneAndNewsId)) {
                                    // 检查礼品是否发放完毕
                                    if (byPrizeCodeAndTelephone.getPushNews().getPrizeTotal() <= userPrizeService.count(byPrizeCodeAndTelephone.getPushNews().getId())) {
                                        replyMessage.append("亲！您的手有点慢哟，礼品已全部发送完，下次请及时输入礼品代码。");
                                    } else {
                                        // 调用第三方接口发放流量币，并记录接口返回结果
                                        byPrizeCodeAndTelephone.setPrizeResult(
                                                thirdPartService.convert2LiuLiangJia(textArray[0], byPrizeCodeAndTelephone.getPushNews().getPrizeNumber()));
                                        byPrizeCodeAndTelephone.setOpenId(inTextMsg.getFromUserName());
                                        byPrizeCodeAndTelephone.setLastUpdateTime(DateTimeUtil.getCurrentTimeSeconds());
                                        userPrizeService.saveAndFlush(byPrizeCodeAndTelephone);
                                        // 告知用户领礼品成功
                                        if ("ok".equals(byPrizeCodeAndTelephone.getPrizeResult())) {
                                            replyMessage.append("亲！中国移动").append(byPrizeCodeAndTelephone.getPushNews().getPrizeNumber())
                                                    .append("MB流量以流量币形式已经存入您的“内蒙古移动流量加”个人账户，请查收。");
                                        } else {
                                            replyMessage.append("亲！您的手机号码【").append(textArray[0])
                                                    .append("】不符合“内蒙古移动流量加”平台的要求，具体原因请到“我的礼品”－“已领礼品”中查看。");
                                        }
                                    }
                                } else {
                                    //告知用户手机号已经领取过图文的礼品
                                    replyMessage.append("亲！您的手机号【").append(textArray[0]).append("】已于【")
                                            .append(StringUtil.convertSeconds2String(byTelephoneAndNewsId.getLastUpdateTime(), "yyyy年MM月dd日 HH:mm"))
                                            .append("】使用代码【").append(byTelephoneAndNewsId.getPrizeCode())
                                            .append("】领取了礼品【")
                                            .append(byTelephoneAndNewsId.getPushNews().getPrizeNumber())
                                            .append(byTelephoneAndNewsId.getPushNews().getPrize().getName())
                                            .append("】，好东西不能独享，赶快告诉亲朋好友吧！");
                                }
                            } else {
                                // 告知用户微信号已经领过图文的礼品
                                replyMessage.append("亲！您的微信号已于【")
                                        .append(StringUtil.convertSeconds2String(byOpenIdAndNewsId.getLastUpdateTime(), "yyyy年MM月dd日 HH:mm"))
                                        .append("】使用手机号【").append(byOpenIdAndNewsId.getTelephone())
                                        .append("】和代码【").append(byOpenIdAndNewsId.getPrizeCode())
                                        .append("】领取过礼品【")
                                        .append(byOpenIdAndNewsId.getPushNews().getPrizeNumber())
                                        .append(byOpenIdAndNewsId.getPushNews().getPrize().getName())
                                        .append("】，好东西不能独享，赶快告诉亲朋好友吧！");
                            }
                        }
                        OutTextMsg outTextMsg = new OutTextMsg(inMsg);
                        outTextMsg.setContent(replyMessage.toString());
                        return outTextMsg;
                    } else {
                        // 未找到手机号对应的礼品代码
                        OutTextMsg outTextMsg = new OutTextMsg(inMsg);
                        outTextMsg.setContent("亲！您输入的礼品代码有误，请点击“我的礼品”－“未领礼品”查看礼品代码并正确输入。");
                        return outTextMsg;
                    }
                }
            }
        }
        return null;
    }

    public WechatHandler getMyself() {
        return this;
    }
}
